import $ from 'jquery'
export default {
    state: {
        id:"",
        username:"",
        photo:"",
        token:"",
        socket:null,
        is_login:false,

    },
    getters: {
    },
    mutations: {
        updateSocket(state, socket){
            state.socket = socket;
        },
        updateUser(state,user){
            state.id = user.id,
            state.username = user.username,
            state.photo = user.photo,
            state.is_login = user.is_login
        },
        updateToken(state, token){
            state.token = token
        }
    },
    actions: {
        login(context,data){
            $.ajax({
                url:"http://127.0.0.1:3000/api/user/account/token/",
                type:"post",
                data:{
                  username:data.username,
                  password:data.password,
                },
                success(resp){
                    if(resp.error_message === "success"){
                        localStorage.setItem("jwt_token",resp.token);
                        context.commit("updateToken", resp.token);
                        data.success(resp);
                        // const socketUrl = `wss://app6955.acapp.acwing.com.cn/websocket/${resp.token}/`
                        // context.commit("updateSocket",new WebSocket(socketUrl))
                    }
                    else{
                        data.error(resp);
                    }
                },
                error(resp){
                  data.error(resp);
                }
              });
        },
        getInfo(context,data){
                $.ajax({
                    url:"http://127.0.0.1:3000/api/user/account/info/",
                    type:'get',
                    headers:{
                      Authorization:"Bearer " + context.state.token
                    },
                    success(resp){
                        if(resp.error_message === "success"){
                            context.commit("updateUser",{
                                ...resp,
                                is_login:true
                            })
                            data.success();
                        }else{
                            data.error();
                        }
                    },
                    error(){
                        data.error();
                    }
                  });
        },
        logout(context){
            localStorage.removeItem("jwt_token");
            context.commit("updateToken","");
            context.commit("updateSocket",null);
            context.commit("updateUser",{
                id:'',
                username:'',
                password:'',
                photo:'',
                is_login:false
            })
        },
    },
    modules: {
    }
}